const upng = require('./UPNG.js')

function btoa(string) {
  var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="
    string = String(string);
    var bitmap, a, b, c,
        result = "", i = 0,
        rest = string.length % 3; // To determine the final padding

    for (; i < string.length;) {
        if ((a = string.charCodeAt(i++)) > 255
                || (b = string.charCodeAt(i++)) > 255
                || (c = string.charCodeAt(i++)) > 255)
            throw new TypeError("Failed to execute 'btoa' on 'Window': The string to be encoded contains characters outside of the Latin1 range.");

        bitmap = (a << 16) | (b << 8) | c;
        result += b64.charAt(bitmap >> 18 & 63) + b64.charAt(bitmap >> 12 & 63)
                + b64.charAt(bitmap >> 6 & 63) + b64.charAt(bitmap & 63);
    }

    // If there's need of padding, replace the last 'A's with equal signs
    return rest ? result.slice(0, rest - 3) + "===".substring(rest) : result;
};

function arrayBufferToBase64(buffer) {
	var binary = '';
	var bytes = new Uint8Array(buffer);
	var len = bytes.byteLength;
	for (var i = 0; i < len; i++) {
        binary += String.fromCharCode(bytes[i]);
    }
    return btoa(binary);
    // return "data:image/png;base64," + btoa(binary);
}

Page({
  data: {
    videoSrc: null,
    flash: 'on',
    devicePosition: 'back',

  },

  onLoad() {
    this.ctx = mp.createCameraContext()
  },

  startFrame() {
    if (this._startFrame) return
    this._startFrame = true
    let now = Date.now()
    let id = 0
    const listener = this.ctx.onCameraFrame((res) => {
      if ((Date.now() - now) > 8000) {
      console.log('4s', res)
        now = Date.now()
        let pngData = upng.encode([res.data], res.width, res.height)
        const path = `${mp.env.USER_DATA_PATH}/test-${id}.png`
        const b64 = arrayBufferToBase64(pngData)
        mp.getFileSystemManager().writeFileSync(path, b64, 'base64')
        id++
        this.setData({
          url: path
        })

      }
    })
    listener.start()
  },



  takePhoto1() {
 
    this.ctx.takePhoto({
      quality: 'low',
      success: (res) => {
        console.log(res);
        console.log("takePhoto success回调")
        this.setData({
          src: res.tempImagePath
        })
        mp.getImageInfo({
          src: res.tempImagePath,
          success(res){
            console.log(res)
            mp.showModal({
              title: "宽高比："+res.width+"*"+res.height+'图片类型:'+res.type
            })
          }
        })
      },
      fail(res){
        console.log(res)
        console.log("takePhoto fail回调")
      },
      complete(res){
        console.log(res)
        console.log("takePhoto complete回调")
      }

    })
  },


  startRecord() {
    this.ctx.startRecord({
      success: (res) => {
        console.log('startRecord')
      },
      fail(res){
        console.log("开始录制失败的回调",res)
      },
      complete(res){
        console.log("开始录制 complete",res)
      }
    })
  },
  stopRecord() {
    this.ctx.stopRecord({
//      compressed:true,

      success: (res) => {
        console.log("停止录制",res)
        this.setData({
          src: res.tempThumbPath,
          videoSrc: res.tempVideoPath
        })
        mp.saveVideoToPhotosAlbum({
          filePath: res.tempVideoPath,
          success(res){
            console.log("保存到本地",res)
          },
          fail(res){
            console.log(0)
            console.log('保存失败',res)
          }
        })
      },
      fail(res){
        console.log("停止录制失败",res)
      },
      complete(res){
        console.log("stop 录制 complete",res)
      }
    })
  },

  saveVedio(){
    mp.downloadFile({
      url: 'https://dn-odum9helk.qbox.me/spjc/1.mp4',
      success(res) {
        console.log('下载视频成功')
        mp.saveVideoToPhotosAlbum({
          filePath: res.tempFilePath,
          success(res){
            console.log('http路径保存',res)
          }
        })
      },
      fail(res) {
        console.log('下载视频失败', res)
      }
    })
    
  },

  cchangedevicePosition(e){
    this.setData({
      devicePosition: e.detail.value
    }),
    mp.showToast({
      title: "当前摄像头朝向: " + e.detail.value,
      icon: "none"
    })
  },



  bindchangeflash(e){
    this.setData({
      flash: e.detail.value
    }),
    mp.showToast({
      title: "当前闪关灯模式: " + e.detail.value,
      icon: "none"
    })
  },

  bindinitdone(data) {
    console.log('bindinitdone camera初始化完成', data)
  },

  bindstop(){
    console.log('摄像头在非正常终止时触发，如退出后台等情况----触发了')
  },
  binderror(){
    console.log('用户不允许使用摄像头时======触发了')
  },

  bindscancode(){
    console.log("bindscancode扫码识别成功")
  },

})
